﻿using JYH.Business;
using JYH.Data;
using JYH.DataAccess;
using JYH.Framework;
using JYH.Model;
using JYH.Model.API;
using Microsoft.AspNetCore.Cors;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OfficeOpenXml.FormulaParsing.Excel.Functions.DateTime;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing.Drawing2D;
using System.Dynamic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.NetworkInformation;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Http;
using System.Web.Security;
using System.Web.Services.Description;
using System.Web.UI.WebControls;

namespace JYH.Web.MES.Controllers
{
    [EnableCors("AllowAll")] // 应用于整个控制器
    public class SYSController : ApiController
    {
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="UserInfo"></param>
        /// <returns></returns>
        [EnableCors("AllowSpecificOrigin")]
        [HttpPost]
        public HttpResponseMessage Login([FromBody] SysUserInfo info)
        {
            ResponseJson<SysUserInfo> json = new ResponseJson<SysUserInfo>();
            json.Code = 200;
            json.Message = string.Empty;
            json.Items = new List<SysUserInfo>();
            string Msg = string.Empty;
            var response = Request.CreateResponse(HttpStatusCode.OK, json);

            try
            {
                SysUserInfoBLL bLL = new SysUserInfoBLL();

                SysUserInfo user = bLL.Login(info, out Msg);

                if (user != null)
                {
                    json.Items.Add(user);

                    #region 记住账号

                    CookieHelper.WriteCookie(user.UserNO);
                    //CookieHelper.WriteCookie("Language", langStr);

                    #endregion 记住账号

                    #region 生成票据并跳转到首页

                    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, user.UserNO, DateTime.Now, DateTime.Now.AddDays(7), true, DateTime.Now.ToString());
                    // FormsAuthenticationTicket lang = new FormsAuthenticationTicket(1, "Language", DateTime.Now, DateTime.Now.AddDays(7), true, langStr);
                    string cookieStr = FormsAuthentication.Encrypt(ticket);//加密票据

                    var cookie = new CookieHeaderValue(FormsAuthentication.FormsCookieName, cookieStr)
                    {
                        Expires = ticket.Expiration, // 设置Cookie的过期时间
                        Domain = Request.RequestUri.Host, // 设置Cookie的域
                        Path = FormsAuthentication.FormsCookiePath, // 设置Cookie的路径
                        HttpOnly = false // 设置Cookie为HttpOnly，防止被JavaScript访问
                    };
                    List<CookieHeaderValue> cookies = new List<CookieHeaderValue>();
                    cookies.Add(cookie);
                    response.Headers.AddCookies(cookies);

                    #endregion 生成票据并跳转到首页
                }
                else
                {
                    json.Code = 500;
                    json.Message = Msg;

                    response = Request.CreateResponse(HttpStatusCode.OK, json);
                    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    return response;
                }
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
                json.Items = new List<SysUserInfo>();

                response = Request.CreateResponse(HttpStatusCode.OK, json);
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                return response;
            }

            response = Request.CreateResponse(HttpStatusCode.OK, json);
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            return response;
        }

        /// <summary>
        /// 获取WEB菜单
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [EnableCors("AllowSpecificOrigin")]
        [HttpPost]
        public HttpResponseMessage GetWebMenu([FromBody] UserMenu info)
        {
            ResponseJson<UserMenu> json = new ResponseJson<UserMenu>();
            json.Code = 200;
            json.Message = string.Empty;
            json.Items = new List<UserMenu>();
            string Msg = string.Empty;
            var response = Request.CreateResponse(HttpStatusCode.OK, json);
            if ((info == null))
            {
                json.Code = 500;
                json.Message = "参数格式错误";
                response = Request.CreateResponse(HttpStatusCode.OK, json);
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                return response;
            }

            try
            {
                //  UserMenu usermenu = JsonConvert.DeserializeObject<UserMenu>(JsonConvert.SerializeObject(info));
                UserMenu usermenu = new UserMenu();
                usermenu.UserNO = info.UserNO;
                usermenu.MenuGroup = info.MenuGroup;
                SysMenuInfoBLL bLL = new SysMenuInfoBLL();
                List<SysMenuInfo> Menus = new List<SysMenuInfo>();
                Menus = bLL.GetMenu(usermenu.UserNO, "0", out Msg);

                if (Menus != null)
                {
                    var topItems = Menus.Where(e => string.IsNullOrEmpty(e.UpMenuID) && e.NameSpace == usermenu.MenuGroup).ToList();
                    //字类
                    var ItemUp = Menus.Where(e => !string.IsNullOrEmpty(e.UpMenuID) && e.NameSpace == usermenu.MenuGroup).ToList();
                    StringBuilder AddBuer = new StringBuilder();
                    AddBuer.Append("  <div class=\"easyui-accordion\" data-options=\"border: false\" style=\"width: 100%; height: 650px; \">").Append("\r\n");
                    foreach (var item in topItems)
                    {
                        AddBuer.Append("<div title=\"" + item.MenuName + "\" data-options=\"iconCls: 'icon-bianji'\" style=\"overflow: auto; \">").Append("\r\n");
                        AddBuer.AppendLine("<ul class=\"easyui-tree\">").Append("\r\n");
                        var ItemEX = ItemUp.FindAll(x => x.UpMenuID == item.MenuID);
                        if (ItemEX.Any())
                        {
                            foreach (var upitem in ItemEX)
                            {
                                AddBuer.Append("<li><a href=\"#\" onclick=\"addTab('" + upitem.MenuName + "','" + upitem.MenuUrl + "')\">" + upitem.MenuName + "</a></li>").Append("\r\n");
                            }
                        }
                        AddBuer.Append("</ul>").Append("\r\n");
                        AddBuer.Append("</div>").Append("\r\n");
                    }
                    AddBuer.Append("</div>").Append("\r\n");
                    json.Items = new List<UserMenu>();
                    UserMenu menu = new UserMenu();
                    menu.HtmlMenu = AddBuer.ToString();
                    json.Items.Add(menu);
                    response = Request.CreateResponse(HttpStatusCode.OK, json);
                    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    return response;
                }
                else
                {
                    json.Code = 500;
                    json.Message = Msg;

                    response = Request.CreateResponse(HttpStatusCode.OK, json);
                    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    return response;
                }
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
                json.Items = new List<UserMenu>();

                response = Request.CreateResponse(HttpStatusCode.OK, json);
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                return response;
            }
        }

        /// <summary>
        /// 获取WEB菜单
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [EnableCors("AllowSpecificOrigin")]
        [HttpPost]
        public HttpResponseMessage GetPageLanguage([FromBody] Translation info)
        {
            ResponseJson<object> json = new ResponseJson<object>();
            json.Code = 200;
            json.Message = string.Empty;
            json.Items = new List<object>();
            string Msg = string.Empty;
            Database db = DB.D();
            var response = Request.CreateResponse(HttpStatusCode.OK, json);
            if ((info == null))
            {
                json.Code = 500;
                json.Message = "参数格式错误";
                response = Request.CreateResponse(HttpStatusCode.OK, json);
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                return response;
            }

            try
            {
                string JsonData = JsonConvert.SerializeObject(info);
                //JsonData.Replace('\',' ');
                SysLanguageInfo LanguageInfo = JsonConvert.DeserializeObject<SysLanguageInfo>(JsonData);
                Sql sql = new Sql();
                sql.Append(";Select SysLanguageInfo.* From SysLanguageInfo");

                sql.Where("(SysLanguageInfo.PageName='" + LanguageInfo.PageName + "' or SysLanguageInfo.PageName='Public')");

                var LanguageNO = "zh-CN";
                if (!string.IsNullOrEmpty(LanguageInfo.LanguageNO))
                {
                    LanguageNO = LanguageInfo.LanguageNO;
                }
                sql.Where("SysLanguageInfo.LanguageNO='" + LanguageNO + "'");
                sql.OrderBy("SysLanguageInfo.ObjectName");
                List<SysLanguageInfo> Languages = new List<SysLanguageInfo>();
                Languages = db.Fetch<SysLanguageInfo>(sql);

                var uniqueLanguages = Languages
                        .GroupBy(p => new { p.ObjectName, p.LanguageNO })
                        .Select(g => g.First())
                        .ToList();
                dynamic result = new ExpandoObject();
                // var obj = new DynamicProperties();
                if (uniqueLanguages.Count > 0)
                {
                    var resultDict = result as IDictionary<string, object>;

                    foreach (var lang in uniqueLanguages)
                    {
                        resultDict[$"{lang.ObjectName}"] = lang.LangName;
                    }
                }
                json.Items.Add(result);
                //  UserMenu usermenu = JsonConvert.DeserializeObject<UserMenu>(JsonConvert.SerializeObject(info));
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
                json.Items = new List<object>();
            }
            response = Request.CreateResponse(HttpStatusCode.OK, json);
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            return response;
        }

        /// <summary>
        /// ERP数据同步
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [EnableCors("AllowSpecificOrigin")]
        [HttpPost]
        public HttpResponseMessage SynchronousData([FromBody] dynamic info)
        {
            ResponseJson<object> json = new ResponseJson<object>();
            json.Code = 200;
            json.Message = string.Empty;
            json.Items = new List<object>();
            string Msg = string.Empty;
            Database db = DB.D();
            var response = Request.CreateResponse(HttpStatusCode.OK, json);
            if ((info == null))
            {
                json.Code = 500;
                json.Message = "参数格式错误";
                response = Request.CreateResponse(HttpStatusCode.OK, json);
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                return response;
            }

            try
            {
                string JsonData = JsonConvert.SerializeObject(info);
                //JsonData.Replace('\',' ');
                SynchronousInfo LanguageInfo = JsonConvert.DeserializeObject<SynchronousInfo>(JsonData);
                object[] args = { LanguageInfo.Date, LanguageInfo.NO, Msg };
                SyncData.SynchronousData("", LanguageInfo.SynchronousName, args, out Msg);
                if (string.IsNullOrEmpty(Msg))
                {
                    Msg = "Synchronous Access";
                }
                json.Message = Msg;
                //  UserMenu usermenu = JsonConvert.DeserializeObject<UserMenu>(JsonConvert.SerializeObject(info));
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
                json.Items = new List<object>();
            }
            response = Request.CreateResponse(HttpStatusCode.OK, json);
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            return response;
        }


        /// <summary>
        /// 单据回抛ERP
        /// </summary>
        /// <param name="Info">{"FunctionName":FunctionName,"NO":NO}</param>
        /// <returns></returns>
        [EnableCors("AllowSpecificOrigin")]
        [HttpPost]
        public HttpResponseMessage BackToErp([FromBody] dynamic Info)
        {
            ResponseJson<object> json = new ResponseJson<object>();
            json.Code = 200;
            json.Message = string.Empty;
            json.Items = new List<object>();
            string Msg = string.Empty;
            Database db = DB.D();
            var response = Request.CreateResponse(HttpStatusCode.OK, json);
            if ((Info == null))
            {
                json.Code = 500;
                json.Message = "参数格式错误";
                response = Request.CreateResponse(HttpStatusCode.OK, json);
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                return response;
            }

            try
            {
                string JsonData = JsonConvert.SerializeObject(Info);
                //JsonData.Replace('\',' ');
                BackToErpData LanguageInfo = JsonConvert.DeserializeObject<BackToErpData>(JsonData);
                object[] args = { LanguageInfo.NO, Msg };
                SyncData.BackToERP("", LanguageInfo.FunctionName, args, out Msg);
                if (string.IsNullOrEmpty(Msg))
                {
                    Msg = "Synchronous Access";
                }
                json.Message = Msg;
                //  UserMenu usermenu = JsonConvert.DeserializeObject<UserMenu>(JsonConvert.SerializeObject(info));
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
                json.Items = new List<object>();
            }
            response = Request.CreateResponse(HttpStatusCode.OK, json);
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            return response;
        }

        /// <summary>
        /// 用户信息查询（通配查询）
        /// </summary>
        /// <param name="rows">每页记录数</param>
        /// <param name="page">当前页码</param>
        /// <param name="UserNO">用户账号</param>
        /// <param name="UserName">用户姓名</param>
        /// <param name="order">排序方式</param>
        /// <param name="sort">排序字段</param>
        /// <returns></returns>
        [EnableCors("AllowSpecificOrigin")]
        [HttpGet]
        public IHttpActionResult QueryUserInfo(int rows, int page, string UserNO, string UserName, string order, string sort)
        {
            Sql sql = new Sql();
            // 用于存储查询结果的列表
            List<SysUserInfo> list = new List<SysUserInfo>();
            // 存储最终返回的 JSON 字符串
            var lists = "";
            // 用于存储操作消息
            string Msg = string.Empty;
            // 查询结果的总记录数
            long total = 0;

            try
            {
                // 创建业务逻辑层实例
                SysUserInfoBLL bll = new SysUserInfoBLL();

                // 如果物料名称不为空，则添加模糊查询条件
                if (!string.IsNullOrEmpty(UserNO))
                {
                    sql.Append("Where (SysUserInfo.UserNO Like '%" + UserNO + "%') ");
                }

                // 如果物料编号不为空，则添加模糊查询条件
                if (!string.IsNullOrEmpty(UserName))
                {
                    sql.Append("Where SysUserInfo.UserName Like '%" + UserName + "%'");
                }

                // 如果有指定排序字段和顺序，则按指定方式排序
                if (!string.IsNullOrEmpty(sort) && !string.IsNullOrEmpty(order))
                {
                    sql.OrderBy(sort + "  " + order);
                }
                else
                {
                    // 默认按创建时间升序排序
                    sql.OrderBy("SysUserInfo.CreateTime Desc,SysUserInfo.UserNO ");
                }

                // 执行分页查询
                list = bll.PagedQuery(page, rows, sql, out total, out Msg);

                // 将查询结果转换为 JSON 格式
                var json = ConvertJson<SysUserInfo>.ListToJson(list);

                // 构建返回的 JSON 字符串，包含总记录数和当前页的数据
                lists = "{\"total\":" + total + ",\"rows\":" + json + "}";
            }
            catch
            {
                // 异常处理（当前未做具体处理，建议记录日志）
            }

            // 返回查询结果
            return Ok(lists);
        }

        /// <summary>
        /// 获取所用菜单并转还TreeGrid格式的数据
        /// </summary>
        /// <returns></returns>
        [EnableCors("AllowSpecificOrigin")]
        [HttpGet]
        public IHttpActionResult QueryMenuToTreeGrid()
        {
            SysMenuInfoBLL bll = new SysMenuInfoBLL();
            TreeGrid tg = new TreeGrid();
            List<SysMenuInfo> menus = new List<SysMenuInfo>();
            List<TreeGridMenu> GridMenua = new List<TreeGridMenu>();
            try

            {
                menus = bll.GetMenu();
                List<SysMenuInfo> pmenus = menus.FindAll(p => string.IsNullOrEmpty(p.UpMenuID)).ToList().OrderBy(o => o.MenuNO).ToList();
                string UpMenuID = string.Empty;
                for (int i = 0; i < pmenus.Count; i++)
                {
                    TreeGridMenu tgm = new TreeGridMenu();
                    tgm.id = i + 1;
                    tgm.MenuID = pmenus[i].MenuID;
                    tgm.MenuNO = pmenus[i].MenuNO;
                    tgm.MenuName = pmenus[i].MenuName;
                    tgm.MenuUrl = pmenus[i].MenuUrl;
                    tgm.UpMenuID = pmenus[i].UpMenuID;
                    tgm.MenuType = pmenus[i].MenuType;
                    tgm.ClassName = pmenus[i].ClassName;
                    tgm.NameSpace = pmenus[i].NameSpace;
                    tgm.IconName = pmenus[i].IconName;
                    tgm.RState = pmenus[i].RState;
                    List<SysMenuInfo> cmenus = menus.FindAll(p => p.UpMenuID == pmenus[i].MenuID).ToList().OrderBy(o => o.MenuNO).ToList();
                    if (cmenus == null || cmenus.Count == 0)
                    {
                        tgm.state = "open";
                    }
                    else
                    {
                        List<TreeMenu> tms = new List<TreeMenu>();
                        for (int j = 0; j < cmenus.Count; j++)
                        {
                            TreeMenu tm = new TreeMenu();
                            tm.id = 10000 * (i + 1) + j;
                            tm.MenuID = cmenus[j].MenuID;
                            tm.MenuNO = cmenus[j].MenuNO;
                            tm.MenuName = cmenus[j].MenuName;
                            tm.MenuUrl = cmenus[j].MenuUrl;
                            tm.UpMenuID = cmenus[j].UpMenuID;
                            tm.MenuType = cmenus[j].MenuType;
                            tm.ClassName = cmenus[j].ClassName;
                            tm.NameSpace = cmenus[j].NameSpace;
                            tm.IconName = cmenus[j].IconName;
                            tm.RState = cmenus[j].RState;
                            tms.Add(tm);
                        }
                        tgm.children = tms;
                        tgm.state = "closed";
                    }

                    GridMenua.Add(tgm);
                }
                tg.total = GridMenua.Count.ToString();
                tg.rows = GridMenua;
                // 假设你有一个数据库上下文

                return Ok(tg);
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        /// <summary>
        /// 获取所有菜单(List对象)
        /// </summary>
        /// <param name="MenuID"></param>
        /// <returns></returns>
        [EnableCors("AllowSpecificOrigin")]
        [HttpGet]
        public IHttpActionResult GetMenuInfo(string MenuID, string IsTop)
        {
            SysMenuInfoBLL bll = new SysMenuInfoBLL();
            List<SysMenuInfo> infos = new List<SysMenuInfo>();
            try
            {
                Sql sql = new Sql();
                sql.Append(bll.SqlSelect);
                if (string.Equals(IsTop, "1"))
                {
                    sql.Where("SysMenuInfo.UpMenuID is null");
                }
                if (!string.IsNullOrEmpty(MenuID))
                {
                    sql.Where("SysMenuInfo.MenuID='" + MenuID + "'");
                }
                sql.OrderBy(@"SysMenuInfo.MenuType,ISNULL( SysMenuInfo.NameSpace,''),
                          ISNULL( UpMenuInfo.MenuNO, UpMenuInfo.MenuNO),SysMenuInfo.MenuNO");
                infos = bll.myDataBase.Fetch<SysMenuInfo>(sql);
                if (string.IsNullOrEmpty(MenuID))
                {
                    SysMenuInfo obj = new SysMenuInfo();
                    obj.MenuName = "No TopMenu";
                    infos.Insert(0, obj);
                }

                return Ok(infos);
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [EnableCors("AllowSpecificOrigin")]
        [HttpPost]
        public HttpResponseMessage SaveMenuInfo([FromBody] SysMenuInfo info)
        {
            ResponseJson<SysMenuInfo> json = new ResponseJson<SysMenuInfo>();
            json.Code = 200;
            json.Message = string.Empty;
            json.Items = new List<SysMenuInfo>();
            var response = Request.CreateResponse(HttpStatusCode.OK, json);

            try
            {
                string Msg = string.Empty;
                SysMenuInfoBLL bLL = new SysMenuInfoBLL();
                bool res = bLL.SaveMenuInfo(info, out Msg);
                if (!res)
                {
                    json.Message = "Failed:" + Msg;
                    json.Code = 500;
                }
                else
                {
                    json.Message = "Operation Successful";
                }
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
                json.Items = new List<SysMenuInfo>();

                response = Request.CreateResponse(HttpStatusCode.OK, json);
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                return response;
            }

            response = Request.CreateResponse(HttpStatusCode.OK, json);
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            return response;
        }

        /// <summary>
        /// 删除功能菜单（检查用户菜单和菜单按钮）
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [EnableCors("AllowSpecificOrigin")]
        [HttpPost]
        public HttpResponseMessage DeleteMenuInfo([FromBody] SysMenuInfo info)
        {
            ResponseJson<SysMenuInfo> json = new ResponseJson<SysMenuInfo>();
            json.Code = 200;
            json.Message = string.Empty;
            json.Items = new List<SysMenuInfo>();
            var response = Request.CreateResponse(HttpStatusCode.OK, json);

            try
            {
                string Msg = string.Empty;
                SysMenuInfoBLL bLL = new SysMenuInfoBLL();
                bool res = bLL.Delete(info.MenuID, out Msg);
                if (!res)
                {
                    json.Message = "Failed:" + Msg;
                    json.Code = 500;
                }
                else
                {
                    json.Message = "Operation Successful";
                }
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
                json.Items = new List<SysMenuInfo>();

                response = Request.CreateResponse(HttpStatusCode.OK, json);
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                return response;
            }

            response = Request.CreateResponse(HttpStatusCode.OK, json);
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            return response;
        }

        /// <summary>
        /// 用户信息保存
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [EnableCors("AllowSpecificOrigin")]
        [HttpPost]
        public HttpResponseMessage SaveUserInfo([FromBody] SysUserInfo info)
        {
            ResponseJson<SysUserInfo> json = new ResponseJson<SysUserInfo>();
            json.Code = 200;
            json.Message = string.Empty;
            json.Items = new List<SysUserInfo>();
            var response = Request.CreateResponse(HttpStatusCode.OK, json);

            try
            {
                string Msg = string.Empty;
                SysUserInfoBLL bLL = new SysUserInfoBLL();
                bool res = bLL.SaveUserInfo(info, out Msg);
                if (!res)
                {
                    json.Message = "Failed:" + Msg;
                    json.Code = 500;
                }
                else
                {
                    json.Message = "Operation Successful";
                }
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
                json.Items = new List<SysUserInfo>();

                response = Request.CreateResponse(HttpStatusCode.OK, json);
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                return response;
            }

            response = Request.CreateResponse(HttpStatusCode.OK, json);
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            return response;
        }

        /// <summary>
        /// 账号审核
        /// </summary>
        /// <param name="infos"></param>
        /// <returns></returns>
        [EnableCors("AllowSpecificOrigin")]
        [HttpPost]
        public HttpResponseMessage ApproveUserInfo([FromBody] dynamic infos)
        {
            ResponseJson<SysUserInfo> json = new ResponseJson<SysUserInfo>();
            json.Code = 200;
            json.Message = "Operation Successful";
            json.Items = new List<SysUserInfo>();
            var response = Request.CreateResponse(HttpStatusCode.OK, json);

            try
            {
                string Msg = string.Empty;
                SysUserInfoBLL bLL = new SysUserInfoBLL();
                if (infos == null)
                {
                    json.Message = "Failed: Please Select One User";
                    json.Code = 500;
                }
                else
                {
                    List<SysUserInfo> lst = new List<SysUserInfo>();
                    var items = JsonConvert.DeserializeObject(infos);
                    foreach (var item in items)
                    {
                        lst.Add(new SysUserInfo
                        {
                            UserID = (string)item.UserID,          // 强制类型转换
                            UserNO = (string)item.UserNO     // 需处理可能的无效转换
                        });
                    }
                    ;

                    bool res = bLL.ChangeState(lst, "1", out Msg);
                    if (!res)
                    {
                        json.Message = "Failed:" + Msg;
                        json.Code = 500;
                    }
                    else
                    {
                        json.Message = "Operation Successful";
                    }
                }
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
                json.Items = new List<SysUserInfo>();

                response = Request.CreateResponse(HttpStatusCode.OK, json);
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                return response;
            }

            response = Request.CreateResponse(HttpStatusCode.OK, json);
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            return response;
        }

        /// <summary>
        /// 账号暂停
        /// </summary>
        /// <param name="infos"></param>
        /// <returns></returns>
        [EnableCors("AllowSpecificOrigin")]
        [HttpPost]
        public HttpResponseMessage PauseUserInfo([FromBody] dynamic infos)
        {
            ResponseJson<SysUserInfo> json = new ResponseJson<SysUserInfo>();
            json.Code = 200;
            json.Message = "Operation Successful";
            json.Items = new List<SysUserInfo>();
            var response = Request.CreateResponse(HttpStatusCode.OK, json);

            try
            {
                string Msg = string.Empty;
                SysUserInfoBLL bLL = new SysUserInfoBLL();
                if (infos == null)
                {
                    json.Message = "Failed: Please Select One User";
                    json.Code = 500;
                }
                else
                {
                    List<SysUserInfo> lst = new List<SysUserInfo>();
                    var items = JsonConvert.DeserializeObject(infos);
                    foreach (var item in items)
                    {
                        lst.Add(new SysUserInfo
                        {
                            UserID = (string)item.UserID,          // 强制类型转换
                            UserNO = (string)item.UserNO     // 需处理可能的无效转换
                        });
                    }
                    ;

                    bool res = bLL.ChangeState(lst, "8", out Msg);

                    if (!res)
                    {
                        json.Message = "Failed:" + Msg;
                        json.Code = 500;
                    }
                    else
                    {
                        json.Message = "Operation Successful";
                    }
                }
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
                json.Items = new List<SysUserInfo>();

                response = Request.CreateResponse(HttpStatusCode.OK, json);
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                return response;
            }

            response = Request.CreateResponse(HttpStatusCode.OK, json);
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            return response;
        }

        /// <summary>
        /// 密码重置
        /// </summary>
        /// <param name="infos"></param>
        /// <returns></returns>
        [EnableCors("AllowSpecificOrigin")]
        [HttpPost]
        public HttpResponseMessage ResetUserInfo([FromBody] dynamic infos)
        {
            ResponseJson<SysUserInfo> json = new ResponseJson<SysUserInfo>();
            json.Code = 200;
            json.Message = "Operation Successful";
            json.Items = new List<SysUserInfo>();
            var response = Request.CreateResponse(HttpStatusCode.OK, json);

            try
            {
                string Msg = string.Empty;
                SysUserInfoBLL bLL = new SysUserInfoBLL();
                if (infos == null)
                {
                    json.Message = "Failed: Please Select One User";
                    json.Code = 500;
                }
                else
                {
                    List<SysUserInfo> lst = new List<SysUserInfo>();
                    var items = JsonConvert.DeserializeObject(infos);
                    foreach (var item in items)
                    {
                        lst.Add(new SysUserInfo
                        {
                            UserID = (string)item.UserID,          // 强制类型转换
                            UserNO = (string)item.UserNO     // 需处理可能的无效转换
                        });
                    }
                    bool res = bLL.Reset(lst, out Msg);
                    if (!res)
                    {
                        json.Message = "Failed:" + Msg;
                        json.Code = 500;
                    }
                    else
                    {
                        json.Message = "Operation Successful";
                    }
                }
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
                json.Items = new List<SysUserInfo>();

                response = Request.CreateResponse(HttpStatusCode.OK, json);
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                return response;
            }

            response = Request.CreateResponse(HttpStatusCode.OK, json);
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            return response;
        }

        /// <summary>
        /// 保存角色对象
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [EnableCors("AllowSpecificOrigin")]
        [HttpPost]
        public HttpResponseMessage SaveRoleInfo([FromBody] SysRoleInfo info)
        {
            ResponseJson<SysRoleInfo> json = new ResponseJson<SysRoleInfo>();
            json.Code = 200;
            json.Message = "Operation Successful";
            json.Items = new List<SysRoleInfo>();
            var response = Request.CreateResponse(HttpStatusCode.OK, json);
            try
            {
                string Msg = string.Empty;
                SysRoleInfoBLL bLL = new SysRoleInfoBLL();
                bool res = bLL.SaveRoleInfo(info, out Msg);
                if (!res)
                {
                    json.Message = "Failed:" + Msg;
                    json.Code = 500;
                }
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
            }
            response = Request.CreateResponse(HttpStatusCode.OK, json);
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            return response;
        }

        /// <summary>
        /// 查询角色对象列表（依据编码和名称通配查询）
        /// </summary>
        /// <param name="rows">每页记录数</param>
        /// <param name="page">当前页码</param>
        /// <param name="RoleNO">角色编码</param>
        /// <param name="RoleName">角色名称</param>
        /// <param name="order"></param>
        /// <param name="sort"></param>
        /// <returns></returns>
        [EnableCors("AllowSpecificOrigin")]
        [HttpGet]
        public IHttpActionResult QueryRoleInfo(int rows, int page, string RoleNO, string RoleName, string order, string sort)
        {
            Sql sql = new Sql();
            // 用于存储查询结果的列表
            List<SysRoleInfo> list = new List<SysRoleInfo>();
            // 存储最终返回的 JSON 字符串
            var lists = "";
            // 用于存储操作消息
            string Msg = string.Empty;
            // 查询结果的总记录数
            long total = 0;

            try
            {
                // 创建业务逻辑层实例
                SysRoleInfoBLL bll = new SysRoleInfoBLL();

                // 如果物料名称不为空，则添加模糊查询条件
                if (!string.IsNullOrEmpty(RoleNO))
                {
                    sql.Append("Where (SysRoleInfo.RoleNO Like '%" + RoleNO + "%') ");
                }

                // 如果物料编号不为空，则添加模糊查询条件
                if (!string.IsNullOrEmpty(RoleName))
                {
                    sql.Append("Where SysRoleInfo.RoleName Like '%" + RoleName + "%'");
                }

                // 如果有指定排序字段和顺序，则按指定方式排序
                if (!string.IsNullOrEmpty(sort) && !string.IsNullOrEmpty(order))
                {
                    sql.OrderBy(sort + "  " + order);
                }
                else
                {
                    // 默认按创建时间升序排序
                    sql.OrderBy("SysRoleInfo.CreateTime Desc,SysRoleInfo.RoleNO ");
                }

                // 执行分页查询
                list = bll.PagedQuery(page, rows, sql, out total, out Msg);

                // 将查询结果转换为 JSON 格式
                var json = ConvertJson<SysRoleInfo>.ListToJson(list);

                // 构建返回的 JSON 字符串，包含总记录数和当前页的数据
                lists = "{\"total\":" + total + ",\"rows\":" + json + "}";
            }
            catch
            {
                // 异常处理（当前未做具体处理，建议记录日志）
            }

            // 返回查询结果
            return Ok(lists);
        }

        /// <summary>
        /// 批量删除角色信息
        /// </summary>
        /// <param name="infos">角色列表</param>
        /// <returns></returns>
        [EnableCors("AllowSpecificOrigin")]
        [HttpPost]
        public HttpResponseMessage DeleteRoleInfo([FromBody] dynamic infos)
        {
            ResponseJson<SysRoleInfo> json = new ResponseJson<SysRoleInfo>();
            json.Code = 200;
            json.Message = "Operation Successful";
            json.Items = new List<SysRoleInfo>();
            var response = Request.CreateResponse(HttpStatusCode.OK, json);

            try
            {
                string Msg = string.Empty;
                SysRoleInfoBLL bLL = new SysRoleInfoBLL();
                if (infos == null)
                {
                    json.Message = "Failed: Please Select One User";
                    json.Code = 500;
                }
                else
                {
                    List<SysRoleInfo> lst = new List<SysRoleInfo>();
                    var items = JsonConvert.DeserializeObject(infos);
                    foreach (var item in items)
                    {
                        lst.Add(new SysRoleInfo
                        {
                            RoleID = (string)item.RoleID,          // 强制类型转换
                            RoleNO = (string)item.RoleNO     // 需处理可能的无效转换
                        });
                    }
                    bool res = bLL.Delete(lst, out Msg);
                    if (!res)
                    {
                        json.Message = "Failed:" + Msg;
                        json.Code = 500;
                    }
                    else
                    {
                        json.Message = "Operation Successful";
                    }
                }
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
                json.Items = new List<SysRoleInfo>();

                response = Request.CreateResponse(HttpStatusCode.OK, json);
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                return response;
            }

            response = Request.CreateResponse(HttpStatusCode.OK, json);
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            return response;
        }

        /// <summary>
        /// 获取角色菜单
        /// </summary>
        /// <param name="RoleNO">角色编号</param>
        /// <param name="RoleID">角色ID</param>
        /// <returns></returns>
        [EnableCors("AllowSpecificOrigin")]
        [HttpGet]
        public IHttpActionResult QueryRoleMenuInfo(string RoleNO, string RoleID)
        {
            SysRoleInfo role = new SysRoleInfo
            {
                RoleNO = RoleNO,
                RoleID = RoleID
            };
            Sql sql = new Sql();
            // 用于存储查询结果的列表
            List<SysRoleMenu> list = new List<SysRoleMenu>();
            // 存储最终返回的 JSON 字符串
            var lists = "";
            // 用于存储操作消息
            string Msg = string.Empty;
            // 查询结果的总记录数
            long total = 0;

            try
            {
                // 创建业务逻辑层实例
                SysRoleInfoBLL bll = new SysRoleInfoBLL();

                // 如果物料名称不为空，则添加模糊查询条件
                if (!string.IsNullOrEmpty(RoleNO))
                {
                    sql.Append("Where (SysRoleInfo.RoleNO = '" + RoleNO + "' or SysRoleInfo.RoleID = '" + RoleID + "') ");
                }

                // 如果物料编号不为空，则添加模糊查询条件

                // 如果有指定排序字段和顺序，则按指定方式排序

                // 默认按创建时间升序排序
                sql.OrderBy("SysRoleMenu.CreateTime Desc,SysMenuInfo.MenuNO ");

                // 执行分页查询
                list = bll.GetRoleMenuList(role, out Msg);

                // 将查询结果转换为 JSON 格式
                var json = ConvertJson<SysRoleMenu>.ListToJson(list);

                // 构建返回的 JSON 字符串，包含总记录数和当前页的数据
                lists = "{\"total\":" + total + ",\"rows\":" + json + "}";
            }
            catch
            {
                // 异常处理（当前未做具体处理，建议记录日志）
            }

            // 返回查询结果
            return Ok(lists);
        }

        /// <summary>
        /// 获取角色用户
        /// </summary>
        /// <param name="RoleNO">角色编号</param>
        /// <param name="RoleID">角色ID</param>
        /// <returns></returns>
        [EnableCors("AllowSpecificOrigin")]
        [HttpGet]
        public IHttpActionResult QueryRoleUserInfo(string RoleNO, string RoleID)
        {
            SysRoleInfo role = new SysRoleInfo
            {
                RoleNO = RoleNO,
                RoleID = RoleID
            };
            Sql sql = new Sql();
            // 用于存储查询结果的列表
            List<SysRoleUser> list = new List<SysRoleUser>();
            // 存储最终返回的 JSON 字符串
            var lists = "";
            // 用于存储操作消息
            string Msg = string.Empty;
            // 查询结果的总记录数
            long total = 0;

            try
            {
                // 创建业务逻辑层实例
                SysRoleInfoBLL bll = new SysRoleInfoBLL();

                // 如果物料名称不为空，则添加模糊查询条件
                if (!string.IsNullOrEmpty(RoleNO))
                {
                    sql.Append("Where (SysRoleInfo.RoleNO = '" + RoleNO + "' or SysRoleInfo.RoleID = '" + RoleID + "') ");
                }

                // 如果物料编号不为空，则添加模糊查询条件

                // 如果有指定排序字段和顺序，则按指定方式排序

                // 默认按创建时间升序排序
                sql.OrderBy("SysRoleUser.CreateTime Desc,SysUserInfo.UserNO ");

                // 执行分页查询
                list = bll.GetRoleUserList(role, out Msg);

                // 将查询结果转换为 JSON 格式
                var json = ConvertJson<SysRoleUser>.ListToJson(list);

                // 构建返回的 JSON 字符串，包含总记录数和当前页的数据
                lists = "{\"total\":" + total + ",\"rows\":" + json + "}";
            }
            catch
            {
                // 异常处理（当前未做具体处理，建议记录日志）
            }

            // 返回查询结果
            return Ok(lists);
        }

        /// <summary>
        /// 依据角色ID获取用户列表（包含不在此角色下的用户）
        /// </summary>
        /// <param name="RoleID"></param>
        /// <returns></returns>
        [EnableCors("AllowSpecificOrigin")]
        [HttpGet]
        public IHttpActionResult QueryUserInfoByRole(string RoleID)
        {
            List<SysUserInfo> list = new List<SysUserInfo>();
            var lists = "";
            try
            {
                SysRoleInfoBLL bll = new SysRoleInfoBLL();

                string Msg = string.Empty;

                // 执行分页查询
                list = bll.GetUserOfRole(RoleID, out Msg);

                // 将查询结果转换为 JSON 格式
                var json = ConvertJson<SysUserInfo>.ListToJson(list);

                // 构建返回的 JSON 字符串，包含总记录数和当前页的数据
                lists = "{\"total\":" + list.Count + ",\"rows\":" + json + "}";
            }
            catch
            {
            }

            return Ok(lists);
        }

        /// <summary>
        /// 依据角色ID获取菜单列表（包含不在此角色下的用户）
        /// </summary>
        /// <param name="RoleID"></param>
        /// <returns></returns>
        [EnableCors("AllowSpecificOrigin")]
        [HttpGet]
        public IHttpActionResult QueryMenuInfoByRole(string RoleID)
        {
            List<SysMenuInfo> list = new List<SysMenuInfo>();
            var lists = "";
            try
            {
                SysRoleInfoBLL bll = new SysRoleInfoBLL();

                string Msg = string.Empty;

                // 执行分页查询
                list = bll.GetMenuOfRole(RoleID, out Msg);

                // 将查询结果转换为 JSON 格式
                var json = ConvertJson<SysMenuInfo>.ListToJson(list);

                // 构建返回的 JSON 字符串，包含总记录数和当前页的数据
                lists = "{\"total\":" + list.Count + ",\"rows\":" + json + "}";
            }
            catch
            {
            }

            return Ok(lists);
        }

        /// <summary>
        /// 批量保存角色用户
        /// </summary>
        /// <param name="infos"></param>
        /// <returns></returns>

        [EnableCors("AllowSpecificOrigin")]
        [HttpPost]
        public HttpResponseMessage SaveRoleUser([FromBody] dynamic infos)
        {
            ResponseJson<object> json = new ResponseJson<object>();
            json.Code = 200;
            json.Message = "Operation Successful";
            json.Items = new List<object>();
            var response = Request.CreateResponse(HttpStatusCode.OK, json);

            try
            {
                string Msg = string.Empty;
                SysRoleInfoBLL bLL = new SysRoleInfoBLL();
                if (infos == null)
                {
                    json.Message = "Failed: Please Select One User";
                    json.Code = 500;
                }
                else
                {
                    List<SysUserInfo> lst = new List<SysUserInfo>();
                    var items = JsonConvert.DeserializeObject(infos);
                    SysRoleInfo Role = new SysRoleInfo();
                    foreach (var item in items)
                    {
                        Role = new SysRoleInfo { RoleID = (string)item.RoleID };
                        lst.Add(new SysUserInfo
                        {
                            UserID = (string)item.UserID,          // 强制类型转换
                            IsSelect = (string)item.IsSelect,
                            UserNO = (string)item.UserNO     // 需处理可能的无效转换
                        });
                    }
                    bool res = bLL.SaveRoleUser(Role, lst, out Msg);
                    if (!res)
                    {
                        json.Message = "Failed:" + Msg;
                        json.Code = 500;
                    }
                    else
                    {
                        json.Message = "Operation Successful";
                    }
                }
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
                json.Items = new List<object>();
            }

            response = Request.CreateResponse(HttpStatusCode.OK, json);
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            return response;
        }

        /// <summary>
        /// 批量保存角色用户
        /// </summary>
        /// <param name="infos"></param>
        /// <returns></returns>

        [EnableCors("AllowSpecificOrigin")]
        [HttpPost]
        public HttpResponseMessage SaveRoleMenu([FromBody] dynamic infos)
        {
            ResponseJson<object> json = new ResponseJson<object>();
            json.Code = 200;
            json.Message = "Operation Successful";
            json.Items = new List<object>();
            var response = Request.CreateResponse(HttpStatusCode.OK, json);

            try
            {
                string Msg = string.Empty;
                SysRoleInfoBLL bLL = new SysRoleInfoBLL();
                if (infos == null)
                {
                    json.Message = "Failed: Please Select One User";
                    json.Code = 500;
                }
                else
                {
                    List<SysMenuInfo> lst = new List<SysMenuInfo>();
                    var items = JsonConvert.DeserializeObject(infos);
                    SysRoleInfo Role = new SysRoleInfo();
                    foreach (var item in items)
                    {
                        Role = new SysRoleInfo { RoleID = (string)item.RoleID };
                        lst.Add(new SysMenuInfo
                        {
                            MenuID = (string)item.MenuID,          // 强制类型转换
                            MenuNO = (string)item.MenuNO,          // 需处理可能的无效转换
                            IsSelect = (string)item.IsSelect
                        });
                    }
                    bool res = bLL.SaveRoleMenu(Role, lst, out Msg);
                    if (!res)
                    {
                        json.Message = "Failed:" + Msg;
                        json.Code = 500;
                    }
                    else
                    {
                        json.Message = "Operation Successful";
                    }
                }
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
                json.Items = new List<object>();
            }

            response = Request.CreateResponse(HttpStatusCode.OK, json);
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            return response;
        }

        /// <summary>
        /// 查询参数列表
        /// </summary>
        /// <param name="rows">每页显示的行数</param>
        /// <param name="page">当前请求的页码</param>
        /// <param name="ParaNO">编号</param>
        /// <param name="ParaName">名称</param>
        /// <param name="order">排序方式（ASC 或 DESC）</param>
        /// <param name="sort">排序字段名称</param>
        /// <returns>返回分页查询结果，包含总记录数和当前页数据</returns>
        [HttpGet]
        public IHttpActionResult QueryParaInfo(int rows, int page, string ParaNO, string ParaName, string order, string sort)
        {
            // 初始化 SQL 构造器
            Sql sql = new Sql();
            // 用于存储查询结果的列表
            List<SysParaInfo> list = new List<SysParaInfo>();
            // 存储最终返回的 JSON 字符串
            var lists = "";
            // 用于存储操作消息
            string Msg = string.Empty;
            // 查询结果的总记录数
            long total = 0;
            bool IsEmpty = false;
            try
            {
                // 创建业务逻辑层实例
                SysParaInfoBLL bll = new SysParaInfoBLL();
                if (!string.IsNullOrEmpty(ParaNO))
                {
                    sql.Append($"Where SysParaInfo.ParaNO like '%{ParaNO}%'");
                    IsEmpty = true;
                }
                if (!string.IsNullOrEmpty(ParaName))
                {
                    sql.Append($"Where SysParaInfo.ParaName like '%{ParaName}%'");
                    IsEmpty = true;
                }
                if (!IsEmpty)
                {
                    sql.Append("Where 1=1 ");
                }
                sql.Append($"Where SysParaInfo.RState<>'99'");
                if (string.IsNullOrEmpty(sort))
                    sort = "desc";
                if (string.IsNullOrEmpty(order))
                    order = "CreateTime";

                sql.OrderBy($"SysParaInfo.{order} {sort}");
                // 执行分页查询
                list = bll.PagedQuery(page, rows, sql, out total, out Msg);

                // 将查询结果转换为 JSON 格式
                var json = ConvertJson<SysParaInfo>.ListToJson(list);

                // 构建返回的 JSON 字符串，包含总记录数和当前页的数据
                lists = "{\"total\":" + total + ",\"rows\":" + json + "}";
            }
            catch
            {
                // 异常处理（当前未做具体处理，建议记录日志）
            }

            // 返回查询结果
            return Ok(lists);
        }

        /// <summary>
        /// 删除参数列表
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult DeleteSysParaInfo([FromBody] List<SysParaInfo> info)
        {
            StringBuilder sb = new StringBuilder();
            string Msg = "操作成功!";
            try
            {
                SysParaInfoBLL bll = new SysParaInfoBLL();
                string Ids = "";
                foreach (var item in info)
                {
                    Ids += "'" + item.ParaID + "',";
                }
                Ids = Ids.Substring(0, Ids.Length - 1);
                sb.Append("Update SysParaInfo Set RState='99' Where  SysParaInfo.ParaID in (" + Ids + ")");
                if (sb.Length > 0)
                    bll.myDataBase.Execute(sb.ToString());
            }
            catch (Exception ex)
            {
                return Content(HttpStatusCode.InternalServerError, ex.ToString());
            }
            return Ok(Msg);
        }

        /// <summary>
        /// 保存参数列表
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult SaveSysParaInfo([FromBody] SysParaInfo info)
        {
            Sql sql = new Sql();
            SysParaInfo obj = new SysParaInfo();
            SysParaInfoBLL bll = new SysParaInfoBLL();
            StringBuilder sb = new StringBuilder();
            try
            {
                obj = null;
                var user = SysUserInfoBLL.GetCookieUser().UserName;
                var currentTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                if (!string.IsNullOrEmpty(info.ParaID))
                {
                    sql = new Sql();
                    sql.Append(bll.SqlSelect);
                    sql.Append($"Where SysParaInfo.ParaID='{info.ParaID}'");
                    obj = bll.myDataBase.SingleOrDefault<SysParaInfo>(sql);
                    obj.ParaNO = info.ParaNO;
                    obj.ParaName = info.ParaName;
                    obj.RType = info.RType;
                    obj.RState = "1";
                    obj.UpdateTime = currentTime;
                    obj.UpdateUser = user;
                    sb.Append(BusinessTool.GetUpdateSql(obj));
                }
                if (obj == null)
                {
                    obj = new SysParaInfo();
                    obj.ParaID = Guid.NewGuid().ToString();
                    obj.CreateTime = currentTime;
                    obj.CreateUser = user;
                    obj.ParaNO = info.ParaNO;
                    obj.ParaName = info.ParaName;
                    obj.RType = info.RType;
                    obj.RState = "1";
                    obj.UpdateTime = currentTime;
                    obj.UpdateUser = user;
                    sb.Append(BusinessTool.GetInsertSql(obj));
                }
                if (sb.Length > 0)
                {
                    bll.myDataBase.Execute(sb.ToString());
                }
            }
            catch (Exception ex)
            {
                return Content(HttpStatusCode.InternalServerError, ex.ToString());
            }
            return Ok();
        }

        /// <summary>
        /// 获取参数列表
        /// </summary>
        /// <returns>返回分页查询结果，包含总记录数和当前页数据</returns>
        [HttpPost]
        public IHttpActionResult GetParaInfo(SysParaInfo info)
        {
            // 初始化 SQL 构造器
            Sql sql = new Sql();
            // 用于存储查询结果的列表
            List<SysParaInfo> list = new List<SysParaInfo>();
            // 存储最终返回的 JSON 字符串
         
            // 用于存储操作消息
            string Msg = string.Empty;
            try
            {
                // 创建业务逻辑层实例
                SysParaInfoBLL bll = new SysParaInfoBLL();
                if (!string.IsNullOrEmpty(info.RType))
                {
                    sql.Append($"Where SysParaInfo.RType = '{info.RType}'");
                }
                sql.Append($"Where SysParaInfo.RState<>'99'");
                // 执行分页查询
                list = bll.NotPagedQuery(sql, out Msg);
                // 将查询结果转换为 JSON 格式
                //lists = ConvertJson<SysParaInfo>.ListToJson(list);
            }
            catch
            {
                // 异常处理（当前未做具体处理，建议记录日志）
            }

            // 返回查询结果
            return Ok(list);
        }

        /// <summary>
        /// 查询参数列表
        /// </summary>
        /// <param name="rows">每页显示的行数</param>
        /// <param name="page">当前请求的页码</param>
        /// <param name="ParaNO">编号</param>
        /// <param name="ParaName">名称</param>
        /// <param name="order">排序方式（ASC 或 DESC）</param>
        /// <param name="sort">排序字段名称</param>
        /// <returns>返回分页查询结果，包含总记录数和当前页数据</returns>
        [HttpGet]
        public IHttpActionResult QueryParaItem(int rows, int page, string ItemName, string ParaID, string RType, string order, string sort)
        {
            // 初始化 SQL 构造器
            Sql sql = new Sql();
            // 用于存储查询结果的列表
            List<SysParaItem> list = new List<SysParaItem>();
            // 存储最终返回的 JSON 字符串
            var lists = "";
            // 用于存储操作消息
            string Msg = string.Empty;
            // 查询结果的总记录数
            long total = 0;
            try
            {
                // 创建业务逻辑层实例
                SysParaItemBLL bll = new SysParaItemBLL();
                if (!string.IsNullOrEmpty(ItemName))
                {
                    sql.Append($"Where SysParaItem.ItemName like '%{ItemName}%'");
                }
                if (!string.IsNullOrEmpty(ParaID))
                {
                    sql.Append($"Where SysParaInfo.ParaID like '%{ParaID}%'");
                }
                else
                {
                    sql.Append($"Where SysParaInfo.RType = '{RType}'");
                }
                sql.Append($"Where SysParaInfo.RState<>'99'");
                if (string.IsNullOrEmpty(sort))
                    sort = "desc";
                if (string.IsNullOrEmpty(order))
                    order = "CreateTime";

                sql.OrderBy($"SysParaItem.{order} {sort}");
                // 执行分页查询
                list = bll.PagedQuery(page, rows, sql, out total, out Msg);

                // 将查询结果转换为 JSON 格式
                var json = ConvertJson<SysParaItem>.ListToJson(list);

                // 构建返回的 JSON 字符串，包含总记录数和当前页的数据
                lists = "{\"total\":" + total + ",\"rows\":" + json + "}";
            }
            catch
            {
                // 异常处理（当前未做具体处理，建议记录日志）
            }

            // 返回查询结果
            return Ok(lists);
        }

        /// <summary>
        /// 保存参数列表
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult SaveParaItem([FromBody] SysParaItem info)
        {
            Sql sql = new Sql();
            SysParaItemBLL bll = new SysParaItemBLL();
            SysParaItem obj = new SysParaItem();
            obj = null;
            StringBuilder sb = new StringBuilder();
     
            try
            {
                var user = SysUserInfoBLL.GetCookieUser().UserName;
                var currentTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                if (!string.IsNullOrEmpty(info.ParaItemID))
                {
                    sql = new Sql();
                    sql.Append(bll.SqlSelect);
                    sql.Append($"Where SysParaItem.ParaItemID='{info.ParaItemID}'");
                    obj = bll.myDataBase.SingleOrDefault<SysParaItem>(sql);

                    obj.OrdIndex = Convert.ToInt32(info.OrdIndex);
                    obj.IsDefault = info.IsDefault;
                    obj.ItemName = info.ItemName;
                    obj.ItemValue = info.ItemValue;
                    obj.UpdateTime = currentTime;
                    obj.UpdateUser = user;
                    sb.Append(BusinessTool.GetUpdateSql(obj));
                }
                else
                {
                    obj = new SysParaItem();
                    obj.ParaItemID = Guid.NewGuid().ToString();
                    obj.ParaID = info.ParaID;
                    obj.CreateTime = currentTime;
                    obj.CreateUser = user;
                    obj.ItemValue = info.ItemValue;
                    obj.OrdIndex = Convert.ToInt32(info.OrdIndex);
                    obj.IsDefault = info.IsDefault;
                    obj.ItemName = info.ItemName;
                    obj.UpdateTime = currentTime;
                    obj.UpdateUser = user;
                    sb.Append(BusinessTool.GetInsertSql(obj));
                }
                if (sb.Length > 0)
                {
                    bll.myDataBase.Execute(sb.ToString());
                }
            }
            catch (Exception ex)
            {
                return Content(HttpStatusCode.InternalServerError, ex.ToString());
            }
            return Ok();
        }

        /// <summary>
        /// 删除参数列表
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult DeleteSysParaItem([FromBody] List<SysParaItem> info)
        {
            StringBuilder sb = new StringBuilder();
            string Msg = "操作成功!";
            try
            {
                SysParaItemBLL bll = new SysParaItemBLL();
                string Ids = "";
                foreach (var item in info)
                {
                    Ids += "'" + item.ParaItemID + "',";
                }
                Ids = Ids.Substring(0, Ids.Length - 1);
                sb.Append("Delete SysParaItem Where  SysParaItem.ParaItemID in (" + Ids + ")");
                if (sb.Length > 0)
                    bll.myDataBase.Execute(sb.ToString());
            }
            catch (Exception ex)
            {
                return Content(HttpStatusCode.InternalServerError, ex.ToString());
            }
            return Ok(Msg);
        }

        /// <summary>
        /// 获取参数列表
        /// </summary>
        /// <returns>返回分页查询结果，包含总记录数和当前页数据</returns>
        [HttpPost]
        public IHttpActionResult GetParaItem([FromBody] JObject requestData)
        {
            // 初始化 SQL 构造器
            Sql sql = new Sql();
            // 用于存储查询结果的列表
            List<SysParaItem> list = new List<SysParaItem>();
            string dynamicParam = requestData["fixedParam"].ToString();
            // 存储最终返回的 JSON 字符串
   
            // 用于存储操作消息
            string Msg = string.Empty;
            try
            {
                // 创建业务逻辑层实例
                SysParaItemBLL bll = new SysParaItemBLL();
                if (!string.IsNullOrEmpty(dynamicParam))
                {
                    sql.Append($"Where SysParaInfo.ParaNO = '{dynamicParam}'");
                }
                sql.Append($"Where SysParaInfo.RState<>'99'");
                // 执行分页查询
                list = bll.NotPagedQuery(sql, out Msg);
                // 将查询结果转换为 JSON 格式
                //lists = ConvertJson<SysParaInfo>.ListToJson(list);
            }
            catch
            {
                // 异常处理（当前未做具体处理，建议记录日志）
            }

            // 返回查询结果
            return Ok(list);
        }
    }
}